package com.dongdongshop.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean (@Autowired DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean  factoryBean = new ShiroFilterFactoryBean();
        //设置安全管理者
        factoryBean.setSecurityManager(defaultWebSecurityManager);

        /*配置过滤器*/
        Map<String,String> filterMap = new LinkedHashMap<>();
        filterMap.put("/login","anon");
        filterMap.put("/sellerLogin","anon");
        filterMap.put("/checkName","anon");
        filterMap.put("/getSellerId","anon");
        filterMap.put("/loginOud","logout");
        filterMap.put("/**","authc");
        /*放置到过滤器链*/
        factoryBean.setLoginUrl("/toLogin");
        factoryBean.setUnauthorizedUrl("/unauthorized");
        factoryBean.setFilterChainDefinitionMap(filterMap);
        return factoryBean;
    }

    /*安全管理器*/
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Autowired LoginRealm loginRealm){
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(loginRealm);
        return manager;
    }

    @Bean
    public LoginRealm loginRealm(@Autowired HashedCredentialsMatcher hashedCredentialsMatcher){
        LoginRealm loginRealm = new LoginRealm();
        loginRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return loginRealm;
    }

    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("MD5");
        matcher.setHashIterations(3);
        matcher.setStoredCredentialsHexEncoded(true);
        return matcher;
    }
}
